﻿using System;
using System.IO;

namespace Bettzueche.RLGlue.Codec.Network {
    /// <summary>
    /// Specialized BinaryReader, who reades Big Endian.<para>
    /// This is necessary, because the RLGlue.exe always writes in BigEndian</para>
    /// </summary>
    class RLGlueBinaryReader : BinaryReader {

        /// <summary>
        /// Initializes a new instance of the <see cref="RLGlueBinaryReader"/> class.
        /// </summary>
        /// <param name="stream">The stream.</param>
        public RLGlueBinaryReader(MemoryStream stream) : base(stream) {
        }

        /// <summary>
        /// Reads a 4-byte signed integer from the current stream and advances the current position of the stream by four bytes.
        /// </summary>
        /// <returns>
        /// A 4-byte signed integer read from the current stream.
        /// </returns>
        /// <exception cref="T:System.IO.EndOfStreamException">The end of the stream is reached. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The stream is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        public override int ReadInt32() {
            byte[] bytes = base.ReadBytes(4);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes);
            return BitConverter.ToInt32(bytes,0);
        }

        /// <summary>
        /// Reads an 8-byte floating point value from the current stream and advances the current position of the stream by eight bytes.
        /// </summary>
        /// <returns>
        /// An 8-byte floating point value read from the current stream.
        /// </returns>
        /// <exception cref="T:System.IO.EndOfStreamException">The end of the stream is reached. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The stream is closed. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        public override double ReadDouble() {
            byte[] bytes = base.ReadBytes(8);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes);
            return BitConverter.ToDouble(bytes, 0);
        }

        //
        //public override byte[] ReadBytes(int count) {
        //    byte[] bytes = base.ReadBytes(8);
        //    if (BitConverter.IsLittleEndian)
        //        Array.Reverse(bytes);
        //    return bytes;
        //}
    }
}
